package com.atguigu.gulimail.order.conf;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Configuration
public class GulimailRequestInterceptor {

    /**
     * 当前主要解决 远程调用，异步线程里没有cookie的问题。
     * feign 在执行的过程中，会有拦截器对request进行封装。
     * 这里设置一个requestInterceptor，在当前异步编排中 就可生效。
     * 换了异步编排。 如果没有提前设置
     *   RequestContextHolder.setRequestAttributes(requestAttributes);
     *   getRequestAtt..为null.
     *
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate template) {

                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes!=null){
                    HttpServletRequest request = attributes.getRequest();
                    //同步请求头数据
                    String cookie = request.getHeader("Cookie");
                    //给新请求同步老请求的cookie;
                    template.header("Cookie", cookie);
                }

            }
        };
    }
}
